/**
 * Created by yyl on 2018/11/21.
 * 自定义 多选框
 */
import React, {Component} from 'react';
import {Icon} from 'antd';
import Immutable from 'immutable';

export default class CheckBox extends Component {
  static defaultProps = {
    data: Immutable.List(),
    onChange: () => {
    },
    radio: false,
    name: '',
    dataName: '',
    disabled : false //不可选，仅用于展示
  };

  render() {
    let data = this.props.data;
    let disabled = this.props.disabled;
    let that = this;
    return (
      <div className="checkbox-ul">
        <ul>
          {
            data.map((item, index) => {
              let className = "";
              if(disabled){
                if(item.get('check')){
                  className = "checkbox-li disabled checked";
                }else{
                  className = "checkbox-li disabled";
                }
              }else if(item.get('check')){
                className = "checkbox-li checked";
              }else{
                className = "checkbox-li";
              }
              return (
                <li onClick={disabled ? null : that._itemClick.bind(that, item.get('value'))} key={index}
                    className={className}>{item.get('text')}
                  <span className="icon-span"><Icon type="check"/></span></li>
              )
            })
          }
        </ul>
      </div>
    )
  }

  _itemClick = (value) => {
    if (this.props.radio) {//单选
      let checkFlag = true;
      let data = this.props.data.map((item) => {
        if (item.get('value') == value) {
          if (item.get('check')) {
            item = item.set('check', false);
          } else {
            checkFlag = false;
            item = item.set('check', true);
          }
        } else {
          item = item.set('check', false);
        }
        return item;
      });
      if(checkFlag){
        value = '';
      }
      this.props.onChange(this.props.name, value, this.props.dataName, data);
    } else {//多选
      let multiValue;
      let data = this.props.data.map((item) => {
        if (item.get('value') == value) {
          if (item.get('check')) {
            item = item.set('check', false);
          } else {
            item = item.set('check', true);
          }
        }
        if (item.get('check')) {
          multiValue = multiValue ? multiValue + "," + item.get("value") : item.get("value");
        }
        return item;
      });
      this.props.onChange(this.props.name, multiValue, this.props.dataName, data);
    }
  }
}